package leetcode_动态规划._09字符串编辑;

/**
 * @author yzh
 * @data 2021/3/22 20:07
 * 字符串编辑距离
 * 思路：
 * |      | ''   | r    | o    | s    |
 * | ---- | ---- | ---- | ---- | ---- |
 * | ''   | 0    | 1    | 2    | 3    |
 * | h    | 1    | 1    | 2    | 3    |
 * | o    | 2    | 2    | 1    | 2    |
 * | r    | 3    | 2    | 2    | 2    |
 * | s    | 4    | 3    | 3    | 2    |
 * | e    | 5    | 4    | 4    | 3    |
 * dp[i][j] : 表示 word1 的前 i 个字符串和 word2 的前 j 个字符串变为相等最少需要几步
 * 由表得出
 *   当两个字符不相等时：dp[i][j] = min(dp[i - 1][j - 1], dp[i][j - 1], dp[i - 1][j] + 1
 *   相等时：dp[i][j] = dp[i - 1][j - 1]
 */
public class _72 {

    public int minDistance(String word1, String word2) {
        int m = word1.length(), n = word2.length();
        int[][] dp = new int[m + 1][n + 1];
        for (int i = 0; i <= m; i++) {
            dp[i][0] = i;
        }
        for (int i = 0; i <= n; i++) {
            dp[0][i] = i;
        }
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (word1.charAt(i - 1) != word2.charAt(j - 1)) {
                    dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;
                } else {
                    dp[i][j] = dp[i - 1][j - 1];
                }
            }
        }
        return dp[m][n];
    }

    // 使用滚动数组
    public int minDistance_upgrade(String word1, String word2) {
        int m = word1.length(), n = word2.length();
        int[][] dp = new int[2][n + 1];
        for (int i = 0; i <= n; i++) {
            dp[0][i] = i;
        }
        int flag = 1;
        for (int i = 1; i <= m; i++) {
            if (i != 0) dp[flag][0] = i;
            int tem = flag == 1 ? -1 : 1;
            for (int j = 1; j <= n; j++) {
                if (word1.charAt(i - 1) != word2.charAt(j - 1))
                    dp[flag][j] = Math.min(dp[flag][j - 1], Math.min(dp[flag + tem][j], dp[flag + tem][j - 1])) + 1;
                else dp[flag][j] = dp[flag + tem][j - 1];
            }
            flag = (flag + 1) % 2;
        }
        return dp[(flag + 1) % 2][n];
    }
}
